package com.zmn.oms.admin.controller.work.modify;

import com.alibaba.fastjson.JSON;
import com.google.common.collect.Lists;
import com.zmn.base.engineer.common.dro.foreign.engineer.ForeignEngineerDetailInfoDRO;
import com.zmn.base.product.common.consts.BaseProductConsts;
import com.zmn.base.product.common.dto.categ.CategProductGroupDRO;
import com.zmn.base.product.common.query.categ.CategProductGroupQuery;
import com.zmn.consts.GlobalConsts;
import com.zmn.common.dto2.ResponseDTO;
import com.zmn.common.utils.date.DateUtil;
import com.zmn.common.utils.number.NumberUtil;
import com.zmn.common.utils.reflect.BeanMapper;
import com.zmn.common.utils.string.StringUtil;
import com.zmn.mcc.common.dto.organize.OrganizeDRO;
import com.zmn.oms.admin.controller.work.WorkBaseController;
import com.zmn.oms.business.interfaces.conf.distributereason.ConfOrderDistributeReasonBService;
import com.zmn.oms.business.interfaces.orderstock.OrderStockBService;
import com.zmn.oms.common.annotation.PageRequestCas;
import com.zmn.oms.common.constant.ConfRedistributeConsts;
import com.zmn.oms.common.constant.OrderConsts;
import com.zmn.oms.common.constant.OrderDistributeConsts;
import com.zmn.oms.common.constant.OrderStatusConsts;
import com.zmn.oms.common.dro.conf.distribute.DistributeArgsDRO;
import com.zmn.oms.common.dro.conf.distribute.DistributeConfigDRO;
import com.zmn.oms.common.dto.ResultDTO;
import com.zmn.oms.common.enums.MasterStockTypeEnum;
import com.zmn.oms.common.exception.OmsBaseException;
import com.zmn.oms.model.bo.order.GridCompanyQueryBO;
import com.zmn.oms.model.bo.product.ProductBO;
import com.zmn.oms.model.dto.order.GridCompanyInfoDTO;
import com.zmn.oms.model.dto.work.distribute.PreDistributeMasterQueryDTO;
import com.zmn.oms.model.dto.work.distribute.PreDistributeMaterVO;
import com.zmn.oms.model.dto.work.modify.OrderDistributeDTO;
import com.zmn.oms.model.entity.conf.distributereason.ConfOrderDistributeReason;
import com.zmn.oms.model.entity.conf.distributereason.ConfOrderDistributeReasonQuery;
import com.zmn.oms.model.entity.detail.OrderDetail;
import com.zmn.oms.model.entity.work.DistributeMasterQuery;
import com.zmn.oms.model.entity.work.OrderWork;
import com.zmn.oms.model.vo.conf.distributereason.ConfOrderDistributeReasonVO;
import com.zmn.oms.model.vo.work.*;
import com.zmn.oms.services.interfaces.conf.distributereason.ConfOrderDistributeReasonService;
import com.zmn.oms.third.taobao.dto.api.TmallApiInvokResult;
import com.zmn.oms.third.taobao.service.TmallService;
import com.zmn.oms.zmn.business.interfaces.order.ZsOrderBService;
import com.zmn.oms.zmn.business.interfaces.work.ZsOrderWorkOperatePermissionBService;
import com.zmn.oms.zmn.business.interfaces.work.customwork.ZsCustomWorkBService;
import com.zmn.oms.zmn.business.interfaces.work.customwork.ZsDistributeWorkBService;
import com.zmn.uuc.common.dro.user.UserDetailDRO;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import javax.validation.Valid;
import java.util.Date;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * 类描述：派单
 *
 * @author liuying
 * @date 2018/12/19 10:51
 */
@Controller
@RequestMapping("/work/modify")
public class WorkDistributeController extends WorkBaseController {

    @Autowired
    private ZsOrderWorkOperatePermissionBService orderWorkOperatePermissionBService;

    @Autowired
    private TmallService tmallService;

    @Autowired
    private ZsCustomWorkBService zsCustomWorkBService;

    @Autowired
    private ZsDistributeWorkBService zsDistributeWorkBService;

    @Resource
    private ConfOrderDistributeReasonBService confOrderDistributeReasonBService;

    @Resource
    private ConfOrderDistributeReasonService confOrderDistributeReasonService;

    @Autowired
    private OrderStockBService orderStockBService;

    @Autowired
    private ZsOrderBService zsOrderBService;

    /**
     * 派单页面
     */
    @RequestMapping(value = "/distribute")
    @PageRequestCas(type = OrderConsts.ORDER_OP_TYPE_DISTRIBUTE)
    public ModelAndView distribute(Long orderId, Long workId) {
        OrderWork orderWork = orderWorkService.findOrderWorkByKey(orderId, workId);
        OrderDetail orderDetail = orderDetailService.findOrderDetailByKey(orderId);

        // 是否网格化派单，而且必须是已确认状态，走网格化派单
        boolean isGridDistribute = zsDistributeWorkBService.isGridDistribute(orderWork);
        if (isGridDistribute) {
            return this.gridDistribute(orderWork, orderDetail);
        }

        return this.spDistribute(orderWork, orderDetail);
    }

    /**
     * 派单页面
     */
    @RequestMapping(value = "/distributeNew")
    @PageRequestCas(type = OrderConsts.ORDER_OP_TYPE_DISTRIBUTE_NEW)
    public ModelAndView distributeNew(Long orderId, Long workId) {
        OrderWork orderWork = orderWorkService.findOrderWorkByKey(orderId, workId);
        OrderDetail orderDetail = orderDetailService.findOrderDetailByKey(orderId);

        ModelAndView mv ;

        // 是否网格化派单，而且必须是已确认状态，走网格化派单
        boolean isGridDistribute = zsDistributeWorkBService.isGridDistribute(orderWork);
        if (isGridDistribute) {
            mv = this.gridDistribute(orderWork, orderDetail);
        } else {
            mv = this.spDistribute(orderWork, orderDetail);
        }

        // 标志是从 派单（新）按钮操作的
        mv.addObject("operateType", OrderConsts.ORDER_OP_TYPE_DISTRIBUTE_NEW);

        return mv;
    }

    /**
     * 强制派单页面
     * @param orderId
     * @param workId
     * @return
     */
    @RequestMapping(value = "/mandatory/distribute")
    public ModelAndView forceDistribute(Long orderId, Long workId) {
        ModelAndView mv = new ModelAndView("work/modify/distribute/grid/biztypec/mandatorydistribute");
        OrderWork orderWork = orderWorkService.findOrderWorkByKey(orderId, workId);
        OrderDetail orderDetail = orderDetailService.findOrderDetailByKey(orderId);
        mv.addObject("plat", orderWork.getPlatWork());
        mv.addObject("orderId", orderWork.getOrderId());
        mv.addObject("workId", orderWork.getWorkId());
        mv.addObject("cityId", orderWork.getCityId());
        // 派单视图对象
        DistributeVO distributeVO = new DistributeVO();
        List<ZsOrderDistributeVO> masterList = zsDistributeWorkBService.listMandatoryDistributeMaster(orderWork, orderDetail);
        distributeVO.setMasterList(masterList);
        distributeVO.setMasterId(orderWork.getMasterId());
        distributeVO.setDistributeRule(OrderDistributeConsts.DISTRIBUTE_RULE_SIMPLE);

        // 隐藏工程师手机号
        this.hideMasterPhone(distributeVO);

        mv.addObject("distributeVO", distributeVO);

        this.setDefaultModelAndView(mv, orderWork);
        return mv;
    }

    /**
     * 保存派单
     */
    @RequestMapping(value = "/save/distribute")
    @ResponseBody
    public ResultDTO saveDistribute(@RequestBody @Valid OrderDistributeDTO distributeDTO) {
        OrderWork orderWork = orderWorkService.findOrderWorkByKey(distributeDTO.getOrderId(), distributeDTO.getWorkId());

        OperatePermissionVO operatePermission = orderWorkOperatePermissionBService.getOperatePermission(distributeDTO.getOrderId(), distributeDTO.getWorkId(), OrderConsts.ORDER_OP_TYPE_DISTRIBUTE);
        if (!operatePermission.getCanOperate()) {
            return ResultDTO.fail(operatePermission.getMsg());
        }

        try {
            // 查询工程师信息
            // todo fubiao
            logger.info("saveDistribute#getEngineerDetailById start [{}]",distributeDTO.getMasterId());
            ResponseDTO<ForeignEngineerDetailInfoDRO> cacheEngineerByEngineerId = engineerListRemoteService.getEngineerDetailById(distributeDTO.getMasterId());
            logger.info("saveDistribute#getEngineerDetailById end [{}]",JSON.toJSONString(cacheEngineerByEngineerId));
            ForeignEngineerDetailInfoDRO baseEngineerDRO = cacheEngineerByEngineerId.getData();
            if (!cacheEngineerByEngineerId.isSuccess() || baseEngineerDRO == null) {
                return ResultDTO.fail("工程师不存在");
            }

            // 天猫勤鸽店且未核销同步派单
            boolean isTmallDistribute = zsDistributeWorkBService.isTmallDistribute(orderWork);

            if (isTmallDistribute) {
                TmallApiInvokResult result = tmallService.syncOrderDistribute(distributeDTO.getOrderId(), baseEngineerDRO.getMobile(),
                        baseEngineerDRO.getRealName(), distributeDTO.getStopOrderTypeCheckReason());

                if (!result.isSuccess()) {
                    return ResultDTO.fail(String.format("[派单失败]-%s", result.getMsg()));
                }
            }

            distributeDTO.setMasterName(baseEngineerDRO.getRealName());
            distributeDTO.setMasterPhone(baseEngineerDRO.getMobile());
            // 设置成已派单
            distributeDTO.setStatus(OrderStatusConsts.WORK_STATUS_DISTRIBUTE);
            // 记录派单路径
            distributeDTO.setDistributeWay(OrderDistributeConsts.DISTRIBUTE_WAY_SP);
            // 记录派单入口
            distributeDTO.setDistributeEntry(OrderDistributeConsts.DISTRIBUTE_ENTRY_ADMIN);
            distributeDTO.setOperateTime(DateUtil.getNow());

            // 设置缘由和责任类型
            this.setLiableTypeAndReasonByDistributeReasonId(distributeDTO);

            if (Objects.equals(distributeDTO.getOperateType(), OrderConsts.ORDER_OP_TYPE_DISTRIBUTE_NEW)) {
                zsCustomWorkBService.saveNewDistribute(distributeDTO);
            } else {
                zsCustomWorkBService.saveDistribute(distributeDTO);
            }
            return ResultDTO.success();
        } catch (OmsBaseException e) {
            e.printStackTrace();
            return ResultDTO.fail(e.getMessage());
        }
    }

    /**
     * 检查派单
     */
    @RequestMapping(value = "/distribute/checkReason")
    @ResponseBody
    public ResultDTO checkDistributeReason(Long orderId, Long workId, Integer masterId, Integer distributeWay) {
        try {
            boolean isGridDistribute = false;
            if (distributeWay == OrderDistributeConsts.DISTRIBUTE_WAY_PLAT) {
                isGridDistribute = true;
            }

            DistributeReasonVO distributeReasonVO = zsDistributeWorkBService.checkDistributeReason(orderId, workId, masterId, isGridDistribute);
            return ResultDTO.success(distributeReasonVO);
        } catch (Exception e) {
            e.printStackTrace();
            return ResultDTO.fail(e.getMessage());
        }
    }

    /** 服务商派单 **************************************************/

    /**
     * 服务商派单页面
     */
    private ModelAndView spDistribute(OrderWork orderWork, OrderDetail orderDetail) {
        ModelAndView mv = new ModelAndView("work/modify/distribute");

        // 获取派单参数
        DistributeArgsDRO distributeArgsDRO = zsDistributeWorkBService.getDistributeParam(orderWork);

        // 派单视图对象
        DistributeVO distributeVO = zsDistributeWorkBService.buildDistributeVO(orderWork, orderDetail, distributeArgsDRO);

        // 非普通派单页面名称
        String newViewName = null;

        // 派单规则
        int distributeRule = OrderDistributeConsts.DISTRIBUTE_RULE_NONE;

        do {
            // 特殊派单
            if (distributeVO.getDistributeBizType() == OrderDistributeConsts.DISTRIBUTE_BIZ_TYPE_SPECIAL) {
                switch (distributeVO.getSpecialDistributeType()) {
                    case OrderDistributeConsts.SPECIAL_DISTRIBUTE_TYPE_SP:
                        // 特殊服务商
                        newViewName = "work/modify/distribute/special/spdistribute";
                        distributeRule = OrderDistributeConsts.DISTRIBUTE_RULE_SPECIAL_SP;
                        break;
                    case OrderDistributeConsts.SPECIAL_DISTRIBUTE_TYPE_TMALL:
                        // 天猫差异派单
                        newViewName = "work/modify/distribute/special/tmalldistribute";
                        distributeRule = OrderDistributeConsts.DISTRIBUTE_RULE_SPECIAL_TMALL;
                        break;
//                    case OrderDistributeConsts.SPECIAL_DISTRIBUTE_TYPE_CHANNEL:
//                        // 渠道指定派单
//                        newViewName = "work/modify/distribute/special/channeldistribute";
//                        distributeRule = OrderDistributeConsts.DISTRIBUTE_RULE_SPECIAL_CHANNEL;
//                        break;
                }

                break;
            }

            // C端派单
            if (distributeVO.getDistributeBizType() == OrderDistributeConsts.DISTRIBUTE_BIZ_TYPE_C) {
                if (distributeVO.isReworkStatus()) {
                    // C端返修
                    newViewName = "work/modify/distribute/biztypec/reworkdistribute";
                    distributeRule = OrderDistributeConsts.DISTRIBUTE_RULE_REWORK;
                } else {
                    // C端新单
                    if (distributeVO.isFairStatus()) {
                        // 公平派单
                        newViewName = "work/modify/distribute/biztypec/fairdistribute";
                        distributeRule = OrderDistributeConsts.DISTRIBUTE_RULE_FAIR;
                    } else {
                        // 推荐派单
                        newViewName = "work/modify/distribute/biztypec/distribute";
                        distributeRule = OrderDistributeConsts.DISTRIBUTE_RULE_RECOMMEND;
                    }
                }
                break;
            }

            // F端派单
            if (distributeVO.getDistributeBizType() == OrderDistributeConsts.DISTRIBUTE_BIZ_TYPE_F) {
                if (distributeVO.isReworkStatus()) {
                    // F端返修
                    newViewName = "work/modify/distribute/biztypef/reworkdistribute";
                    distributeRule = OrderDistributeConsts.DISTRIBUTE_RULE_REWORK;
                } else {
                    // F端新单
                    newViewName = "work/modify/distribute/biztypef/simpledistribute";
                    distributeRule = OrderDistributeConsts.DISTRIBUTE_RULE_SIMPLE;
                }

                break;
            }

        } while (false);

        // 如果为非普通派单页面，设置为新的视图
        if (newViewName != null) {
            mv.setViewName(newViewName);
        }

        mv.addObject("plat", orderWork.getPlatWork());
        mv.addObject("orderId", orderWork.getOrderId());
        mv.addObject("workId", orderWork.getWorkId());
        mv.addObject("companyId", orderWork.getCompanyId());
        mv.addObject("manageCompanyId", orderWork.getManageCompanyId());
        mv.addObject("cityId", orderWork.getCityId());

        // 查询派单工程师
        zsDistributeWorkBService.getOrderDistributeMasterList(orderWork, orderDetail, distributeVO, distributeArgsDRO);
        if (distributeVO.getMasterList() == null) {
            distributeVO.setMasterList(Lists.newArrayListWithCapacity(0));
        }

        if (distributeVO.getRecommendMasterList() == null) {
            distributeVO.setRecommendMasterList(Lists.newArrayListWithCapacity(0));
        }

        // 同位置、同品类工单，已派给工程师
        ZsOrderDistributeVO dutyRecentMaster = zsDistributeWorkBService.findDutyRecentMaster(orderWork, orderDetail, false);
        distributeVO.setDutyRecentMaster(dutyRecentMaster);

        // 设置派单路径为服务商派单
        distributeVO.setDistributeWay(OrderDistributeConsts.DISTRIBUTE_WAY_SP);

        // 设置派单入口为运营后台
        distributeVO.setDistributeEntry(OrderDistributeConsts.DISTRIBUTE_ENTRY_ADMIN);

        // 设置派单模式
        distributeVO.setDistributeRule(distributeRule);

        // 隐藏工程师手机号
        this.hideMasterPhone(distributeVO);

        // 是否开通动态库存城市
        boolean isWhiteCity = orderStockBService.isWhiteWorkCity(orderWork.getCityId());
        distributeVO.setStockCity(isWhiteCity);

        mv.addObject("distributeVO", distributeVO);

        // 设置页面其它数据
        this.setDefaultModelAndView(mv, orderWork);

        return mv;
    }

    /** 网格化派单 **************************************************/

    /**
     * 网格化派单页面
     */
    private ModelAndView gridDistribute(OrderWork orderWork, OrderDetail orderDetail) {
        ModelAndView mv = new ModelAndView("work/modify/distribute/grid/biztypec/distribute");

        // 获取派单参数
        DistributeConfigDRO distributeConfigDRO = zsDistributeWorkBService.getDistributeConfig(orderWork);

        // 派单视图对象
        DistributeVO distributeVO = zsDistributeWorkBService.buildDistributeVO(orderWork, orderDetail, distributeConfigDRO.getPlatDirectlyDistributeArgsDRO(), true);

        // 非普通派单页面名称
        String newViewName = null;

        // 派单规则
        int distributeRule = OrderDistributeConsts.DISTRIBUTE_RULE_NONE;

        do {

            // C端派单
            if (distributeVO.getDistributeBizType() == OrderDistributeConsts.DISTRIBUTE_BIZ_TYPE_C) {
                if (distributeVO.isReworkStatus()) {
                    // C端返修
                    newViewName = "work/modify/distribute/grid/biztypec/reworkdistribute";
                    distributeRule = OrderDistributeConsts.DISTRIBUTE_RULE_REWORK;
                } else {
                    // C端新单
                    if (distributeVO.isFairStatus()) {
                        // 公平派单
                        newViewName = "work/modify/distribute/grid/biztypec/fairdistribute";
                        distributeRule = OrderDistributeConsts.DISTRIBUTE_RULE_FAIR;
                    } else {
                        // 推荐派单
                        newViewName = "work/modify/distribute/grid/biztypec/distribute";
                        distributeRule = OrderDistributeConsts.DISTRIBUTE_RULE_RECOMMEND;
                    }
                }
                break;
            }

        } while (false);

        // 如果为非普通派单页面，设置为新的视图
        if (newViewName != null) {
            mv.setViewName(newViewName);
        }

        mv.addObject("plat", orderWork.getPlatWork());
        mv.addObject("orderId", orderWork.getOrderId());
        mv.addObject("workId", orderWork.getWorkId());
        mv.addObject("cityId", orderWork.getCityId());

        // 查询派单工程师
        zsDistributeWorkBService.gridGetOrderDistributeMasterList(orderWork, orderDetail, distributeVO, distributeConfigDRO);
        if (distributeVO.getMasterList() == null) {
            distributeVO.setMasterList(Lists.newArrayListWithCapacity(0));
        }

        if (distributeVO.getRecommendMasterList() == null) {
            distributeVO.setRecommendMasterList(Lists.newArrayListWithCapacity(0));
        }

        try {
            // 查询用户所属组织架构
            ResponseDTO<OrganizeDRO> organDROResponseDTO = organizeListRemoteService.getByKey(getLoginStaff().getOrgId());
            OrganizeDRO organDRO = organDROResponseDTO.getData();
            if (organDRO != null) {
                boolean isSubCompany = organDRO.getLevel() == null || organDRO.getLevel() > com.zmn.consts.GlobalConsts.LEVEL_2;
                if (isSubCompany) {
                    // 分公司 权限，过滤工程师
                    Integer companyId = organDRO.getCompanyId();
                    logger.info("子公司员工[ID：{}] 所属公司[ID:{}] 需要过滤工程师权限", companyId);

                    // 过滤工程师
                    distributeVO.setMasterList(distributeVO.getMasterList().stream().
                            filter(item -> Objects.equals(companyId, item.getCompanyId()))
                            .collect(Collectors.toList()));

                    distributeVO.setRecommendMasterList(distributeVO.getRecommendMasterList().stream().
                            filter(item -> Objects.equals(companyId, item.getCompanyId()))
                            .collect(Collectors.toList()));
                }
            }
        } catch (Exception ex) {
        }

        // 同位置、同品类工单，已派给工程师
        ZsOrderDistributeVO dutyRecentMaster = zsDistributeWorkBService.findDutyRecentMaster(orderWork, orderDetail, true);
        distributeVO.setDutyRecentMaster(dutyRecentMaster);

        // 设置派单路径为平台直派
        distributeVO.setDistributeWay(OrderDistributeConsts.DISTRIBUTE_WAY_PLAT);

        // 设置派单入口为运营后台
        distributeVO.setDistributeEntry(OrderDistributeConsts.DISTRIBUTE_ENTRY_ADMIN);

        // 设置派单模式
        distributeVO.setDistributeRule(distributeRule);

        // 隐藏工程师手机号
        this.hideMasterPhone(distributeVO);

        // 是否开通动态库存城市
        boolean isWhiteCity = orderStockBService.isWhiteWorkCity(orderWork.getCityId());
        distributeVO.setStockCity(isWhiteCity);

        mv.addObject("distributeVO", distributeVO);
        mv.addObject("vVip", orderDetail.getVvip());
        // 设置页面其它数据
        this.setDefaultModelAndView(mv, orderWork);
        return mv;
    }

    /**
     * 保存网格化派单
     */
    @RequestMapping(value = "/save/grid/distribute")
    @ResponseBody
    public ResultDTO saveGridDistribute(@RequestBody @Valid OrderDistributeDTO distributeDTO) {
        OperatePermissionVO operatePermission = orderWorkOperatePermissionBService.getOperatePermission(distributeDTO.getOrderId(), distributeDTO.getWorkId(), OrderConsts.ORDER_OP_TYPE_DISTRIBUTE);
        if (!operatePermission.getCanOperate()) {
            return ResultDTO.fail(operatePermission.getMsg());
        }

        try {
            // 查询工程师信息
            ResponseDTO<ForeignEngineerDetailInfoDRO> cacheEngineerByEngineerId = engineerListRemoteService.getEngineerDetailById(distributeDTO.getMasterId());
            ForeignEngineerDetailInfoDRO baseEngineerDRO = cacheEngineerByEngineerId.getData();
            if (!cacheEngineerByEngineerId.isSuccess() || baseEngineerDRO == null) {
                return ResultDTO.fail("工程师不存在");
            }

            distributeDTO.setMasterName(baseEngineerDRO.getRealName());
            distributeDTO.setMasterPhone(baseEngineerDRO.getMobile());
            // 设置成已派单
            distributeDTO.setStatus(OrderStatusConsts.WORK_STATUS_DISTRIBUTE);
            // 记录派单路径
            distributeDTO.setDistributeWay(OrderDistributeConsts.DISTRIBUTE_WAY_PLAT);
            // 记录派单入口
            distributeDTO.setDistributeEntry(OrderDistributeConsts.DISTRIBUTE_ENTRY_ADMIN);
            distributeDTO.setOperateTime(DateUtil.getNow());

            // 设置缘由和责任类型
            this.setLiableTypeAndReasonByDistributeReasonId(distributeDTO);

            // 调用派单保存接口
            if (Objects.equals(distributeDTO.getOperateType(), OrderConsts.ORDER_OP_TYPE_DISTRIBUTE_NEW)) {
                zsCustomWorkBService.saveNewDistribute(distributeDTO);
            } else {
                zsCustomWorkBService.saveDistribute(distributeDTO);
            }
            return ResultDTO.success();
        } catch (OmsBaseException e) {
            e.printStackTrace();
            return ResultDTO.fail(e.getMessage());
        }
    }

    /**
     * 派单快照页面
     * @param workId
     * @param snapshotId
     * @return
     */
    @RequestMapping(value = "/distribute/snapshot")
    public ModelAndView distributeSnapshot(Long workId, Long snapshotId) {
        ModelAndView mv = new ModelAndView("work/modify/distribute/distributeSnapshot");
        DistributeSnapshotVO vo = zsDistributeWorkBService.buildDistributeSnapshotVO(workId, snapshotId);
        logger.debug("派单快照：【{}】", JSON.toJSONString(vo));
        mv.addObject("distributeSnapshotVO", vo);
        return mv;
    }

    /**
     * 获取派单工程师
     *
     * @param preDistributeMasterQueryDTO
     * @modifier huangchao 2022/04/01 取消下单计算工程师逻辑 后期可能会重新启用
     */
    @RequestMapping(value = "/pre/distribute/master")
    @ResponseBody
    @Deprecated
    public ResultDTO distributeMaster(@RequestBody PreDistributeMasterQueryDTO preDistributeMasterQueryDTO) {
        logger.debug("distributeMaster preDistributeMasterQueryDTO={}", JSON.toJSONString(preDistributeMasterQueryDTO));
        PreDistributeMaterVO vo = new PreDistributeMaterVO();
        try {
            this.processDistributeMasterQuery(preDistributeMasterQueryDTO);
            DistributeMasterQuery distributeMasterQuery = BeanMapper.map(preDistributeMasterQueryDTO, DistributeMasterQuery.class);
            for (int callCount = 1; callCount < 4; callCount++) {
                preDistributeMasterQueryDTO.setCallCount(callCount);
                this.processQueryParam(preDistributeMasterQueryDTO, distributeMasterQuery);
                logger.debug("zsDistributeWorkBService.getPreDistributeMaster distributeMasterQuery={}", JSON.toJSONString(distributeMasterQuery));
                DistributeVO preDistributeMaster = zsDistributeWorkBService.getPreDistributeMaster(distributeMasterQuery);
                logger.debug("zsDistributeWorkBService.getPreDistributeMaster preDistributeMaster={}", JSON.toJSONString(preDistributeMaster));
                this.processPreDistributeMaterVO(preDistributeMasterQueryDTO, vo, preDistributeMaster);
                if (vo.isExistMater()) {
                    break;
                }
            }
        } catch (Exception e) {
            return ResultDTO.fail(e.getMessage());
        }

        return ResultDTO.success();
    }

    private void processQueryParam(PreDistributeMasterQueryDTO preDistributeMasterQueryDTO, DistributeMasterQuery distributeMasterQuery) {
        switch (preDistributeMasterQueryDTO.getCallCount()) {
            case 2:
                // 一天后8点整时间
                preDistributeMasterQueryDTO.setDutyTime(DateUtil.getDateAndHour(DateUtil.addDays(preDistributeMasterQueryDTO.getDutyTime(), 1), 8));
                break;
            case 3:
                // 二天后8点整时间
                preDistributeMasterQueryDTO.setDutyTime(DateUtil.getDateAndHour(DateUtil.addDays(preDistributeMasterQueryDTO.getDutyTime(), 1), 8));
                break;
        }
        distributeMasterQuery.setDutyTime(preDistributeMasterQueryDTO.getDutyTime());

        if (preDistributeMasterQueryDTO.getCallCount() > 1) {
            distributeMasterQuery.setOnlyOptimalStock(true);
        }else {
            distributeMasterQuery.setOnlyOptimalStock(false);
        }
    }

    private void processPreDistributeMaterVO(PreDistributeMasterQueryDTO preDistributeMasterQueryDTO, PreDistributeMaterVO vo, DistributeVO distributeVO) {
        ZsOrderDistributeVO autoDistributeMaster = distributeVO.getAutoDistributeMaster();
        vo.setExistMater(Objects.nonNull(autoDistributeMaster));
        if (vo.isExistMater()) {
            vo.setDistributeMasterId(autoDistributeMaster.getMasterId());
        }

        switch (preDistributeMasterQueryDTO.getCallCount()) {
            case 1:
                if (!vo.isExistMater()) {
                    break;
                }
                if (Objects.equals(autoDistributeMaster.getStockType(), MasterStockTypeEnum.OPTIMAL_STOCK.getCode())) {
                    vo.setDistributeMasterLog(String.format("%s%s（%s）", "可服务工程师：", autoDistributeMaster.getMasterName(), StringUtil.formatHideMobile(autoDistributeMaster.getMasterPhone())));
                }else if (Objects.equals(autoDistributeMaster.getStockType(), MasterStockTypeEnum.HAVE_STOCK.getCode())) {
                    vo.setDistributeMasterLog(String.format("%s%s（%s）", "当日可服务工程师：", autoDistributeMaster.getMasterName(), StringUtil.formatHideMobile(autoDistributeMaster.getMasterPhone())));
                }
                vo.setDistributeJsonStr(JSON.toJSONString(distributeVO));
                break;
            case 2:
                if (!vo.isExistMater()) {
                    break;
                }
                if (Objects.equals(autoDistributeMaster.getStockType(), MasterStockTypeEnum.OPTIMAL_STOCK.getCode())) {
                    vo.setDistributeMasterLog(String.format("%s%s（%s）", "第二天08:00可服务工程师：", autoDistributeMaster.getMasterName(), StringUtil.formatHideMobile(autoDistributeMaster.getMasterPhone())));
                }
                vo.setDistributeJsonStr(JSON.toJSONString(distributeVO));
                vo.setChangeDutyTime(true);
                break;
            case 3:
                if (!vo.isExistMater()) {
                    vo.setDistributeMasterLog("当天及后两天无工程师可提供服务");
                    break;
                }
                if (Objects.equals(autoDistributeMaster.getStockType(), MasterStockTypeEnum.OPTIMAL_STOCK.getCode())) {
                    vo.setDistributeMasterLog(String.format("%s%s（%s）", "第三天08:00可服务工程师：", autoDistributeMaster.getMasterName(), StringUtil.formatHideMobile(autoDistributeMaster.getMasterPhone())));
                }
                vo.setDistributeJsonStr(JSON.toJSONString(distributeVO));
                vo.setChangeDutyTime(true);
                break;

        }

        if (vo.isChangeDutyTime()) {
            Date dutyTime = preDistributeMasterQueryDTO.getDutyTime();
            String dutyTimeStr = DateUtil.toString(dutyTime, DateUtil.FORMAT_DATETIME);
            vo.setShowDutyTime(dutyTimeStr);
            vo.setDutyTime(dutyTimeStr);
            vo.setIsToday(Objects.equals(DateUtil.getNowFormatted(DateUtil.FORMAT_DATE), DateUtil.toString(dutyTime, DateUtil.FORMAT_DATE)));
        }
    }

    private void processDistributeMasterQuery(PreDistributeMasterQueryDTO preDistributeMasterQueryDTO) throws OmsBaseException {
        ProductBO showProductBO = new ProductBO();
        ProductBO productBO = new ProductBO();
        if (NumberUtil.isNotNullOrZero(preDistributeMasterQueryDTO.getShowProductId())) {
            showProductBO = this.getShowProductByProductId(preDistributeMasterQueryDTO.getShowProductId());
        }
        if (NumberUtil.isNotNullOrZero(preDistributeMasterQueryDTO.getProductId())) {
            productBO = this.getProductByProductId(preDistributeMasterQueryDTO.getProductId());

            // 设置前台产品
            showProductBO = this.getShowProductByProductId(preDistributeMasterQueryDTO.getProductId());
        }
        preDistributeMasterQueryDTO.setOrderType(OrderConsts.ORDER_TYPE_NEW);
        preDistributeMasterQueryDTO.setCategId(productBO.getCategId());
        preDistributeMasterQueryDTO.setShowCategId(showProductBO.getCategId());
        preDistributeMasterQueryDTO.setShowCategOneId(showProductBO.getCategOneId());
        preDistributeMasterQueryDTO.setProductGroupId(productBO.getProductGroupId());
        preDistributeMasterQueryDTO.setShowProductGroupId(showProductBO.getProductGroupId());
        preDistributeMasterQueryDTO.setMainSkillId(preDistributeMasterQueryDTO.getServCategId() + "-" + preDistributeMasterQueryDTO.getShowCategId());
        if (NumberUtil.isNotNullOrZero(productBO.getCategId())) {
            // 后台产品分组
            logger.info("servAssCategoryListRemoteService#getProductGroupByCategId 查询产品分组 入参：servCateg={}, categTwoId={}", preDistributeMasterQueryDTO.getServCategId(), productBO.getCategId());
            CategProductGroupQuery categProductGroupQuery = new CategProductGroupQuery();
            categProductGroupQuery.setBizType(preDistributeMasterQueryDTO.getBizType());
            categProductGroupQuery.setServCategId(preDistributeMasterQueryDTO.getServCategId());
            categProductGroupQuery.setCategId(productBO.getCategId());
            categProductGroupQuery.setShowType(BaseProductConsts.ERP_SHOW_TYPE);
            ResponseDTO<CategProductGroupDRO> categoryProductGroupDROResponseDTO = categServProductListRemoteService.getBasisProductGroupByQuery(categProductGroupQuery);
            logger.info("servAssCategoryListRemoteService#getProductGroupByCategId 查询产品分组 出参：【{}】", categoryProductGroupDROResponseDTO);
            CategProductGroupDRO categorySimpleProductGroupDRO = categoryProductGroupDROResponseDTO.getData();
            if (categorySimpleProductGroupDRO != null) {
                preDistributeMasterQueryDTO.setServProductGroupId(categorySimpleProductGroupDRO.getGroupId());
            }
        } else if (NumberUtil.isNotNullOrZero(showProductBO.getCategId())) {
            // 前台产品分组
            logger.info("servAssCategoryListRemoteService#getProductGroupByShowCategId 查询产品分组 入参：servCateg={}, categTwoId={}", preDistributeMasterQueryDTO.getServCategId(), showProductBO.getCategId());
            CategProductGroupQuery categProductGroupQuery = new CategProductGroupQuery();
            categProductGroupQuery.setBizType(preDistributeMasterQueryDTO.getBizType());
            categProductGroupQuery.setServCategId(preDistributeMasterQueryDTO.getServCategId());
            categProductGroupQuery.setCategId(showProductBO.getCategId());
            categProductGroupQuery.setShowType(BaseProductConsts.EC_SHOW_TYPE);
            ResponseDTO<CategProductGroupDRO> responseDTO = categServProductListRemoteService.getBasisProductGroupByQuery(categProductGroupQuery);
            logger.info("servAssCategoryListRemoteService#getProductGroupByShowCategId 查询产品分组 出参：【{}】", responseDTO);
            CategProductGroupDRO categorySimpleProductGroupDRO = responseDTO.getData();
            if (categorySimpleProductGroupDRO != null) {
                preDistributeMasterQueryDTO.setServProductGroupId(categorySimpleProductGroupDRO.getGroupId());
            }
        }

        // 行政子公司id
        this.processGridCompanyId(preDistributeMasterQueryDTO);

    }

    private void processGridCompanyId(PreDistributeMasterQueryDTO preDistributeMasterQueryDTO){

        GridCompanyQueryBO gridCompanyQueryBO = new GridCompanyQueryBO();
        gridCompanyQueryBO.setCityId(preDistributeMasterQueryDTO.getCityId());
        gridCompanyQueryBO.setDistributeWay(OrderDistributeConsts.DISTRIBUTE_WAY_PLAT);
        gridCompanyQueryBO.setLongitude(preDistributeMasterQueryDTO.getLongitude());
        gridCompanyQueryBO.setLatitude(preDistributeMasterQueryDTO.getLatitude());
        gridCompanyQueryBO.setServCategId(preDistributeMasterQueryDTO.getServCategId());
        gridCompanyQueryBO.setShowCategId(preDistributeMasterQueryDTO.getShowCategId());
        gridCompanyQueryBO.setShowCategOneId(preDistributeMasterQueryDTO.getShowCategOneId());

        GridCompanyInfoDTO gridCompanyInfo = zsOrderBService.getGridCompanyInfo(gridCompanyQueryBO);

        preDistributeMasterQueryDTO.setGridCompanyId(gridCompanyInfo.getGridCompanyId());
    }


    /**
     * 隐藏工程师手机号
     *
     * @param distributeVO
     */
    private void hideMasterPhone(DistributeVO distributeVO) {
        List<ZsOrderDistributeVO> masterList = distributeVO.getMasterList();
        if (CollectionUtils.isEmpty(masterList)) {
            return;
        }

        masterList.forEach(item -> {
            item.setMasterPhone(StringUtil.formatHideMobile(item.getMasterPhone()));
        });
    }

    /**
     * 设置页面参数
     *
     * @param mv
     * @param orderWork
     */
    private void setDefaultModelAndView(ModelAndView mv, OrderWork orderWork) {
        // 改派缘由
        if (NumberUtil.isNotNullOrZero(orderWork.getMasterId())) {
            ConfOrderDistributeReasonQuery query = new ConfOrderDistributeReasonQuery();
            query.setPlat(orderWork.getPlatWork());
            query.setStatus(GlobalConsts.YES);
            query.setApplyType(String.valueOf(ConfRedistributeConsts.REDISTRIBUTE_APPLY_TYPE_ADMIN));
            query.setOrderType(String.valueOf(orderWork.getType()));
            List<ConfOrderDistributeReasonVO> reasonList = confOrderDistributeReasonBService.listByQuery(query);
            logger.info("改派缘由 入参：{}， 出参：{}", JSON.toJSONString(query), JSON.toJSONString(reasonList));
            mv.addObject("distributeReasonList", reasonList);
        }
    }

    /**
     * 设置缘由和责任类型
     *
     * @param distributeDTO
     */
    private void setLiableTypeAndReasonByDistributeReasonId(OrderDistributeDTO distributeDTO) {
        if (Objects.isNull(distributeDTO.getDistributeReasonId())) {
            return;
        }
        ConfOrderDistributeReason confOrderDistributeReason = confOrderDistributeReasonService.findConfById(distributeDTO.getDistributeReasonId());
        if (Objects.isNull(confOrderDistributeReason)) {
            return;
        }

        distributeDTO.setLiableType(confOrderDistributeReason.getLiableType());
        distributeDTO.setDistributeReason(confOrderDistributeReason.getReason());
    }
}
